<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="pageStyle.css" />
<link rel="stylesheet" href="fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
<title>Wolverine Peace Webshop</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" > </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.js"> </script>
<script type="text/javascript" src="verticalSlider.js"> </script>
<script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript" src="jquery.livequery.min.js"></script>
<script type="text/javascript">
function getAsyncReviews() {
	//Subsequent calls to get updates from server
	$.get("PeaceShop", {reviews: "", nonce: new Date()}, function(data) {
		//Retrieve neccesary data from result
		var jData = $(data);
		var jReview = jData.find("review");
		var jUser = jReview.find("user").text();
		var jTemp = jReview.attr("date");
		var jDate = new Date();
		jDate.setTime(jTemp);
		var jComment = jReview.find("comment").text();
		var jName = jReview.find("name").text();
		var jId = jReview.find("id").text();
		
		if(jName !== "") {
			//We only want to display reviews with actual content
			//We get hold on the three divs for reviews, id0 is the oldest review, id1 the second oldest and id2 is the newest
			var lastReview = $("#0");
			var middleReview = $("#1");
			var firstReview = $("#2");
			//Then we remove the oldest review and replace it with the second oldest
			lastReview.empty();
			lastReview.html(middleReview.html());
			//And remove the second oldest and replace it with the formerly newest
			middleReview.empty();
			middleReview.html(firstReview.html());
			//And remove the formerly newest to make room for the review we just received
			firstReview.empty();
			
			//We fill in data
			var content = $("<b><a class='iframe' href='itemInfo.html?item=" + jId + "'>" + jName + "</a></b><br />" + "<div class='user'>" + jUser + "</div><div class='date'>" + jDate.toLocaleString() + "</div><div class='comment'>" + jComment + "</div>");
			//And append to div
			firstReview.append(content);
		}
		//We call method again to make a new GET request to the server to retrieve new updates
		//Some how this call causes IE to loop because getAsyncReviews gets called all the time
		//We have found no way to solve this eventhough we tried using a boolean variable and setTimeout
		getAsyncReviews();
	}, 'xml');
}

function simpleSnip(text) {
	//This simply reduces the length of a text to 600 characters(and adds "..." if the text is longer)
	//We use it to reduce the describtions of items showed at the main page
	var stringLength = text.length;
	if(stringLength > 600) {
		var string = text.substring(0,600) + "...";
		return string;
	} 
	return text;
}

$(function() {
	//Everything inside this function gets called when the page loads
	$.get("PeaceShop", function(data){
		//We make a GET request to retrieve all the items from the server
		var jData = $( data );
		//First we get hold on the root element called productList
		var jProductList = jData.find("productList");
		//And then all the children, which are the actual items
		var jItems = jProductList.children();
		
		jItems.each(
			function( intSectionIndex ) {
				//For each item we execute this function to retrieve data about the item
				var jItem		 = $( this );
				var jItemId		 = jItem.attr("iId");
				var jName		 = jItem.find("name").text();
				var JDescription = jItem.find("description").text();
				var JCategory	 = jItem.find("category").text();
				var jPrice		 = jItem.find("price").text();
				var jPicture	 = jItem.find("pictureURL").text();
				//We setup a few divs to display the item
				var newDiv 		 = $( "<div class='item' category='" + JCategory + "'></div>");
				var clear 		 = $( "<div class='clear'></div>");
				
				if(jName !== "") {
					//If the item is not empty we actually displays something
					//We use a div with a figure tag inside instead of a canvas since canvas is used to draw upon and our
					// images are not to be drawn upon or changed in any other way.
					var pictureDiv = $( "<div class='canvas'></div>" );
					pictureDiv.append("<figure><img src='pictures/"+ jPicture + "' alt='" + jName+ "' /></figure>")
				    newDiv.append(pictureDiv);
					
					//We create more divs to position everything nicely
					newNameDiv	 = $( "<div class='name'></div>" );
					//The link contained in this div is used to get detailed information about the specific item
					newNameDiv.append("<b><a href='itemInfo.html?item=" + jItemId + "' class='iframe'>" + jName + "</a></b>");
					newNameDiv.append("<br />");
					newNameDiv.append("<details>" + simpleSnip(JDescription) + "</details>");
					newDiv.append(newNameDiv);
					newDiv.append("<div class='price'>" + jPrice + "</div>");		
					newDiv.append(clear);
					newLI = $( '<li></li>' );
					$( "#items" ).append(newLI);
					newLI.append(newDiv);
				}
			}	
		);
		//We setup our vertical slider used to navigate through the items
		$( "#slider" ).verticalSlider({
	        numbers: 3		
		});
	 }, 'xml');
	
	//First call to set up reviews
	$.get("PeaceShop", {reviews: "new"}, function(data) {
		//Retrieve data
		var jData = $(data);
		var jReviews = jData.find("reviews");
		var jItem = jReviews.children();
		
		jItem.each(
				function(intSectionIndex) {
					//For each review we receive we do this
					var jReview = $(this);
					var id;
					if(jItem.size() == 1) {
						//We only get 1 review and use the id 2
						id = "#2";
					} else if(jItem.size() == 2) {
						//We only get 2 reviews and avoid putting anything in the oldest(index 0)
						id = "#" + (intSectionIndex + 1);
					} else {
						//We get 3 reviews and use the index to locate the reviews
						id = "#" + intSectionIndex;
					}
					//Get the data from the review
					var newDiv = $(id);
					var jUser = jReview.find("user").text();
					var jTemp = jReview.attr("date");
					var jDate = new Date();
					jDate.setTime(jTemp);
					var jComment = jReview.find("comment").text();
					var jName = jReview.find("name").text();
					var jId = jReview.find("id").text();
					
					if(jName !== "") {
						//If the review is not empty we display it nicely
						var content = $("<b><a class='iframe' href='itemInfo.html?item=" + jId + "'>" + jName + "</a></b><br />"
							+ "<div class='user'><address>" + jUser + "</address></div><div class='date'><time>"
							+ jDate.toLocaleString() + "</time></div>"
							+ "<div class='comment'>" + jComment + "</div>");
						newDiv.append(content);
					}
				}
				);
		
	}, 'xml');
	
	//make a call to the function so that we wait for new reviews to arrive at the server
	getAsyncReviews();
	
	$(".ck").change(function() { 
		//This function is called whenever a checkbox with class ck is changed
		//We use it to hide/show items within a certain category
	    $(".item[category='" + this.id + "']").toggle(this.checked);
	  }).change();
	
	$( ".item" ).live('mousedown', function() {
		$(this).draggable({
			appendTo: "body",
			helper: "clone"
		});
	
	});

	//Put items in the basket if they exist in sessionStorage
	//The variables basket and totalPrice can be used anywhere inside the "main" function called when the page loads
	var basket = sessionStorage.getItem("basket");
	var totalPrice;
	if(!basket || basket.length == 0) {
		//If the basket is not defined yet or it is empty we inialize the variables
		//(We check for length because we want to reset totalPrice to 0 in case the basket is empty but defined)
		totalPrice = 0;
		basket = "";
	} else {
		//We do have items in the storage, get the price first
		totalPrice = parseInt(sessionStorage.getItem("totalPrice"));
		//Then we get the right place in the dom to place the items
		var basketTag = $("#basket ol");
		//Split the basket value
		var items = basket.split(";");
		//Remove the placeholder element since we have items to replace it with
		var placeholder = basketTag.find(".placeholder").remove();
		for(var i=0; i<items.length-1; ++i) {
			//Loop through all items and add them to the basket
			var itemText = items[i];
			jItem = $("<li></li>").text(itemText);
			basketTag.append(jItem);
		}
		//Then we set the total price
		$("#totalPrice").text("Total price: " + totalPrice);
	}
	
	//Making the basked droppable. 
	$( "#basket ol" ).droppable({
		activeClass: "ui-state-default",
		hoverClass: "ui-state-hover",
		tolerance: 'pointer',
		accept: ":not(.ui-sortable-helper)",
		drop: function( event, ui ) {
			$( this ).find( ".placeholder" ).remove();
			var itemText =  ui.draggable.find('b').text() + " (" + ui.draggable.find('.price').text() + "Kr)";
			$( "<li></li>" ).text(itemText).appendTo( this );
			totalPrice += parseInt(ui.draggable.find('.price').text());
			$("#totalPrice").text("Total price: " + totalPrice);
			//Add new item to storage, we use ; to seperate items, assuming that no items contain ; in the name
			basket = basket + itemText + ";";
			sessionStorage.setItem("basket", basket);
			sessionStorage.setItem("totalPrice", totalPrice);
		}
	}).sortable({
		items: "li:not(.placeholder)",
		sort: function() {
			$( this ).removeClass( "ui-state-default" );
		}
	});

	//adding fancybox to all <a> with iframe class
	$("a.iframe").livequery( function(){	
		$(this).fancybox({ 
			'width'				: '70%',
			'height'			: '90%',
	        'autoScale'     	: true,
	        'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			'type'				: 'iframe'
			});
	});
	
	//Add event-listener for click-event to both buttons in the basket(they both clear the basket)
	$(".basket_button").each(function() {
		$(this).click(function() {
			//Get hold on the button name and the items currently in the basket(to be used later)
			var buttomName = $(this).attr("name");		
			var itemsInBasket = $("#basket ol li");
			//Recreate the placeholder element
			var placeholder = $( "<li></li>" ).text("Add your items here");
			placeholder.addClass("placeholder");
			var b = $("#basket ol");
			//Empty the basket
			b.empty();
			//Add the placeholder element
			b.append(placeholder);
			$("#totalPrice").empty();
			//Clear variables and sessionStorage
			basket = "";
			totalPrice = 0;
			sessionStorage.setItem("basket", basket);
			sessionStorage.setItem("totalPrice", totalPrice);
			
			if(buttomName == "buy") {
				//Simulate that the client bought the items
				if(itemsInBasket.first().text() != "Add your items here")
					alert("Your package is packed and shipped");
				else
					alert("Nothing to ship");
			} else {
				//Just empty the basket
				alert("Your basket is empty");
			}
		});
	});
});
</script>
<body>
<div id="wrapper-header">
	<div id="header">
		<H1>PeaceShop</H1>
	</div>
</div>
<div id="content-wrapper">

	<div id="left">
		<h2>Reviews:</h2>
		<aside id="reviews">
			<div id="2" class="review"></div>
			<div id="1" class="review"></div>
			<div id="0" class="review"></div>
		</aside>
	</div>

	<div id="right">
		<h2>Basket:</h2>
		<div id="basket">
			<div> 
				<ol> 
					<li class="placeholder">Add your items here</li> 
				</ol> 
			</div>
			<div id="totalPrice"></div>
			<div class="buttons">
				<button name="reset" class="basket_button" value="reset">Reset</button>
				<button name="buy" class="basket_button" value="buy">Buy</button>
			</div>	
		</div>
	</div>

	<div id="content">
		<div id="categories">
			<input type="checkbox" name="Plants" id="Plants" class="ck" checked="checked" /> Plants
			<input type="checkbox" name="Nuclears" id="Nuclear" class="ck" checked="checked" /> Nuclear
			<input type="checkbox" name="Eletronic" id="Eletronic" class="ck" checked="checked" /> Eletronics
			<input type="checkbox" name="Sport" id="Sport" class="ck" checked="checked" /> Sport
		</div>
		<div class="previous">
			<img class="prevArrow" src="ArrowTop.png">
		</div>
		<div id="slider">
			<!-- Her indsættes alle items fra vores PeachShop vha. jQuery AJAX -->
			<ul id="items"></ul>
		</div>
		<div class="next">
			<img class="nextArrow" src="ArrowBottom.png"/>
		</div>
		
	</div>
	<div class="clear"></div>
</div>
<div id="footer">
	PeachShop
</div>
</body>
</html>
